//
//  KLManualTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/7/8.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLManualTableViewController.h"
#import "KLHelp.h"
#import "HemaConst.h"
#import "KLOpenClockViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "Masonry.h"
#import "JRToast.h"
#import "UIAlertView+Blocks.h"
#include "objc/runtime.h"
#import <objc/message.h>

@interface KLManualTableViewController ()
{
    KLOpenClockViewController *openClockVC;
    UILabel *titleLabel;
    UIActivityIndicatorView *activityIndicator;
    
    CBPeripheral *per;
}
@property (nonatomic,strong) NSMutableArray *locksBlueTooth;
@property (nonatomic,strong) NSTimer *manualOpenTimeOut;
@end

@implementation KLManualTableViewController
-(NSMutableArray *)locksBlueTooth{
    if(!_locksBlueTooth){
        _locksBlueTooth = [NSMutableArray array];
    }
    return _locksBlueTooth;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [[UIView alloc]init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPersArr:) name:@"manual" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openLockComplete:) name:@"openLockComplete" object:nil];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.locksBlueTooth.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 定义唯一标识
    static NSString *CellIdentifier = @"Cell";
    // 通过唯一标识创建cell实例
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    // 判断为空进行初始化  --（当拉动页面显示超过主页面内容的时候就会重用之前的cell，而不会再次初始化）
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    // 对cell 进行简单地数据配置
    per = self.locksBlueTooth[indexPath.row];
    cell.textLabel.text = per.name;
    cell.detailTextLabel.text = @"点击开锁";
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CBCentralManager *manager = [openClockVC valueForKey:@"manager"];
    if(manager.state != 5){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"打开蓝牙来允许“KISSLOCK”连接到锁配件"
                                                        message:nil
                                               cancelButtonItem:[RIButtonItem itemWithLabel:@"设置" action:^{
            NSURL *url = [NSURL URLWithString:@"App-Prefs:root=Bluetooth"];//UIApplicationOpenSettingsURLString为跳往app设置
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];}
        }]
                                               otherButtonItems:[RIButtonItem itemWithLabel:@"好" action:^{
            [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"canShark"];
        }], nil];
        
        [alert show];
        return ;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [openClockVC manualOpenLock:indexPath.row];
    [KLHelp showHUDAddedTo:self.view title:@"正在开锁" details:nil animated:YES];
    self.manualOpenTimeOut = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(manualOpenTimeOut:) userInfo:nil repeats:NO];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0f;
}

#pragma mark - 生命周期方法
-(void)viewWillAppear:(BOOL)animated{
    [self.locksBlueTooth removeAllObjects];
    [self.tableView reloadData];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UITabBarController *tabBarVC = (UITabBarController *)window.rootViewController;
    MMDrawerController *mmdVC = tabBarVC.childViewControllers[0];
    UINavigationController *nav = (UINavigationController *)mmdVC.centerViewController;
    openClockVC = nav.childViewControllers[0];
    
    [openClockVC searchPeripheral:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [openClockVC searchPeripheral:NO];
    [KLHelp hideAllHUDsForView:self.view animated:YES];
    
    [activityIndicator removeFromSuperview];
    [titleLabel removeFromSuperview];
}

- (void)viewDidAppear:(BOOL)animated{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window setBackgroundColor:RGB_UI_COLOR(8, 128, 181)];
    
    //添加标题label
//    titleLabel = [UILabel new];
//    titleLabel.text = @"KISSLOCK";
//    titleLabel.textColor = [UIColor whiteColor];
//    titleLabel.backgroundColor = BB_Blue_Color;
//    titleLabel.font = [UIFont systemFontOfSize:23];
//    titleLabel.textAlignment = NSTextAlignmentCenter;
//    self.navigationItem.titleView = titleLabel;
    
    //添加活动指示器
    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityIndicator.color = RGB_UI_COLOR(8, 128, 181);
    [window addSubview:activityIndicator];
    [activityIndicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(window);
        make.top.mas_equalTo(23);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
    [activityIndicator startAnimating];
}

#pragma mark - 获取所有搜到的蓝牙特征
-(void)getPersArr:(NSNotification *)notify{
    NSDictionary *userInfo = [notify userInfo];
    self.locksBlueTooth = [userInfo objectForKey:@"manaulLocks"];
    [self.tableView reloadData];
}

-(void)openLockComplete:(id)sender{
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC);
    dispatch_after(time, dispatch_get_main_queue(), ^{
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [self.manualOpenTimeOut invalidate];
    });
}

#pragma mark - 手动开锁超时
-(void)manualOpenTimeOut:(id)sender{
    [KLHelp hideAllHUDsForView:self.view animated:YES];
    [openClockVC.manualManager cancelPeripheralConnection:per];
}
@end
